﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using Basic4Net.BusinessRules;
using Basic4Net.Entities;
using Basic4Net.OAWeb.Base;
using Basic4Net.Utility.Common;

namespace Basic4Net.OAWeb.Module_Report
{
    public partial class VacationTeacherReport : BasePage
    {
        private static Amount _amount;
        protected static Amount HAmount
        {
            get { return _amount ?? (_amount = new Amount()); }
        }

        public string strSelHtml = string.Empty;
        private string teachType = string.Empty;

        //合计数值
        protected static string strSumAmountIssued = string.Empty;
        protected static string strSumAmountIssuedPlus = string.Empty;
        protected static string strSumHolidayWork = string.Empty;
        protected static string strSumAmountActual = string.Empty;

        //获取登陆用户ID
        protected int UserID
        {
            get 
            { 
                string userID = Session["UserID"].ToString();
                int outUserID = 0;
                if (int.TryParse(userID, out outUserID))
                    return outUserID;
                return 0;
            }
        }

        protected bool bIsSuper = true;
        protected void Page_Load(object sender, EventArgs e)
        {
            teachType = Request.QueryString["type"].ToString();
            bIsSuper = ExistSuper(UserID);
            if (!IsPostBack)
            {
                BindQueryType();
                BindYearMonth();
                BindData();
            }
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            BindData();
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "Load", "Load();", true);
        }

        protected void ddlQueryType_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selValue = ddlQueryType.SelectedValue;
            if (selValue == "0")
                this.queryKeyWord.Enabled = false;
            else
                this.queryKeyWord.Enabled = true;
            this.queryKeyWord.Text = "";

            if (!string.IsNullOrEmpty(strSumAmountIssued) && bIsSuper)
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "AddSumRow", "AddSumRow(" + strSumAmountIssued + "," + strSumAmountIssuedPlus + "," + strSumHolidayWork + "," + strSumAmountActual + ");", true);
        }

        public List<MeritPayView> GetMeritPayViewList(string teachCode, string teachName, int iTeachType, int year, int month)
        {
            using (DBEntities db = new DBEntities())
            {
                var obj = (from tmp in db.t_MeritPay
                           join ti in db.TEACHERINFO on tmp.TeacherID equals ti.RID into temp1
                           from t in temp1.DefaultIfEmpty()
                           where (tmp.SchoolMark == t.SCHOOLMARK)
                           && (String.IsNullOrEmpty(teachCode.Trim()) ? true : t.TEACHCODE.Contains(teachCode.Trim()))
                           && (String.IsNullOrEmpty(teachName.Trim()) ? true : t.TEACHNAME.Contains(teachName.Trim()))
                           && t.SCHOOLMARK == SchoolMark && (int)tmp.TeachType == iTeachType
                           && (int)tmp.FYear == year && (int)tmp.FMonth == month
                           && (bIsSuper ? true : t.RID == UserID)
                           select new MeritPayView
                           {
                               TeachID = t.RID,
                               TeachCode = t.TEACHCODE,
                               TeachName = t.TEACHNAME,
                               AmountIssued = tmp.AmountIssued,
                               HolidayWork = tmp.HolidayWork,
                               AmountActual = tmp.AmountActual,
                               HolidayWorkContent = tmp.HolidayWorkContent,
                               AmountDifferContent = tmp.AmountDifferContent
                           });
                return (List<MeritPayView>)obj.ToList();
            }
        }

        //绑定Repeater数据
        private void BindData()
        {
            string queryType = ddlQueryType.SelectedValue;
            string queryWord = queryKeyWord.Text;
            string teachCode = null;
            string teachName = null;
            int year = 0, month = 0;
            if (ddlYearMonth.SelectedValue.IndexOf("年") == -1 && ddlYearMonth.SelectedValue.IndexOf("月") == -1)
            {
                this.rpt_TeacherReport.DataSource = new List<MeritPayView>();
                this.rpt_TeacherReport.DataBind();
                return;
            }
            string[] strArr = ddlYearMonth.SelectedValue.Split('年');
            Int32.TryParse(strArr[0], out year);
            Int32.TryParse(strArr[1].Split('月')[0], out month);

            double? dSumAmountIssued = 0.0;
            double? dSumAmountIssuedPlus = 0.0;
            double? dSumHolidayWork = 0.0;
            double? dSumAmountActual = 0.0;

            if(queryType == "1")
                teachCode = queryWord;
            else if(queryType == "2")
                teachName = queryWord;

            int iTeachType = int.Parse(teachType);

            List<MeritPayView> mpView = new List<MeritPayView>();
            mpView = GetMeritPayViewList(teachCode, teachName, iTeachType, year, month);

            DataTable dt = new DataTable();
            System.Reflection.PropertyInfo[] pis = (new MeritPayView()).GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);//获得对象的所有public属性
            for (int j = 0; j < pis.Count(); j++)
            {
                DataColumn col = new DataColumn();
                col.ColumnName = pis[j].Name;
                col.DataType = typeof(string);
                dt.Columns.Add(col);
            }
            for (int i = 0; i < mpView.Count; i++)
            {
                DataRow row = dt.NewRow();
                row["TeachID"] = mpView[i].TeachID.ToString();
                row["TeachCode"] = mpView[i].TeachCode;
                row["TeachName"] = mpView[i].TeachName;
                row["AmountIssued"] = mpView[i].AmountIssued == null ? "" : Math.Round(mpView[i].AmountIssued.Value, 2).ToString();
                row["HolidayWork"] = mpView[i].HolidayWork == null ? "" : Math.Round(mpView[i].HolidayWork.Value, 2).ToString();
                row["AmountActual"] = mpView[i].AmountActual == null ? "" : Math.Round(mpView[i].AmountActual.Value, 2).ToString();
                row["HolidayWorkContent"] = mpView[i].HolidayWorkContent;
                row["AmountDifferContent"] = mpView[i].AmountDifferContent;
                dt.Rows.Add(row);

                dSumAmountIssued += mpView[i].AmountIssued == null ? 0 : Math.Round(mpView[i].AmountIssued.Value, 2);
                dSumAmountIssuedPlus += mpView[i].AmountIssued == null ? 0 : Math.Round(mpView[i].AmountIssued.Value, 2)-600;
                dSumHolidayWork += mpView[i].HolidayWork == null ? 0 : Math.Round(mpView[i].HolidayWork.Value, 2);
                dSumAmountActual += mpView[i].AmountActual == null ? 0 : Math.Round(mpView[i].AmountActual.Value, 2);
            }

            int PageNow = 0;
            DataView dv = dt.DefaultView;
            System.Web.UI.WebControls.PagedDataSource ps = new PagedDataSource();
            ps.DataSource = dv;
            ps.AllowPaging = true;
            ps.PageSize = 20;
            if (this.txt_Go.Text.ToString() == "")
                this.txt_Go.Text = "1";
            if (this.txt_Go.Text.ToString() == "0")
                this.txt_Go.Text = "1";
            if (Convert.ToInt32(this.txt_Go.Text.ToString()) >= ps.PageCount)
                this.txt_Go.Text = ps.PageCount.ToString();
            PageNow = Convert.ToInt32(this.txt_Go.Text.ToString()) - 1;
            ps.CurrentPageIndex = Convert.ToInt32(this.txt_Go.Text.ToString()) - 1;
            
            this.rpt_TeacherReport.DataSource = ps;
            this.rpt_TeacherReport.DataBind();
            this.lbl_ToPage.Text = this.txt_Go.Text.ToString();
            this.lbl_PageCount.Text = ps.PageCount.ToString();

            #region
            //IList<string> dtList = new List<string>();
            //using (DBEntities db = new DBEntities())
            //{
            //    var obj = (from tmp in db.t_MeritPay
            //               join ti in db.TEACHERINFO on tmp.TeacherID equals ti.RID into temp1
            //               from t in temp1.DefaultIfEmpty()
            //               where (tmp.SchoolMark == t.SCHOOLMARK)
            //               && (String.IsNullOrEmpty(teachCode.Trim()) ? true : t.TEACHCODE.Contains(teachCode.Trim()))
            //               && (String.IsNullOrEmpty(teachName.Trim()) ? true : t.TEACHNAME.Contains(teachName.Trim()))
            //               && t.SCHOOLMARK == SchoolMark && (int)tmp.TeachType == iTeachType
            //               && tmp.FYear == year && tmp.FMonth == month
            //               && (bIsSuper ? true : t.RID == UserID)
            //               select new
            //               {
            //                   AmountIssued = tmp.AmountIssued,
            //                   AmountIssuedPlus = tmp.AmountIssued - 600,
            //                   HolidayWork = tmp.HolidayWork,
            //                   AmountActual = tmp.AmountActual,
            //               });

            //    var SumAmountIssued = obj.Select(o => o.AmountIssued).Sum();
            //    var SumAmountIssuedPlus = obj.Select(o => o.AmountIssuedPlus).Sum();
            //    var SumHolidayWork = obj.Select(o => o.HolidayWork).Sum();
            //    var SumAmountActual = obj.Select(o => o.AmountActual).Sum();

            //    dtList.Add(SumAmountIssued == null ? "0" : Math.Round(SumAmountIssued.Value, 2).ToString());
            //    dtList.Add(SumAmountIssuedPlus == null ? "0" : Math.Round(SumAmountIssuedPlus.Value, 2).ToString());
            //    dtList.Add(SumHolidayWork == null ? "0" : Math.Round(SumHolidayWork.Value, 2).ToString());
            //    dtList.Add(SumAmountActual == null ? "0" : Math.Round(SumAmountActual.Value, 2).ToString());
            //}
            #endregion
            if (mpView != null && mpView.Count > 0 && bIsSuper)
            {
                strSumAmountIssued = dSumAmountIssued.ToString();
                strSumAmountIssuedPlus = dSumAmountIssuedPlus.ToString();
                strSumHolidayWork = dSumHolidayWork.ToString();
                strSumAmountActual = dSumAmountActual.ToString();
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "AddSumRow", "AddSumRow(" + dSumAmountIssued.ToString() + "," + dSumAmountIssuedPlus.ToString() + "," + dSumHolidayWork.ToString() + "," + dSumAmountActual.ToString() + ");", true);
            }
        }

        //绑定查询类型
        private void BindQueryType()
        {
            ddlQueryType.Items.Add(new ListItem("所有", "0"));
            ddlQueryType.Items.Add(new ListItem("工号", "1"));
            ddlQueryType.Items.Add(new ListItem("姓名", "2"));
            ddlQueryType.SelectedValue = "0";
            queryKeyWord.Enabled = false;
        }

        //绑定年月DDL
        private void BindYearMonth()
        {
            int holType = 1, fPlan = 1;
            IList<string> dtList = new List<string>();
            dtList = GetAmountYearMonth(SchoolMark, holType, fPlan);
            if (dtList == null || dtList.Count < 1)
            {
                ddlYearMonth.Items.Add(new ListItem("--当前没有绩效工资的历史数据--", "-1"));
                return;
            }
            ddlYearMonth.DataSource = dtList;
            ddlYearMonth.DataBind();
        }

        /// <summary>
        /// 获取所有审核月
        /// </summary>
        /// <param name="schoolMark">schoolMark</param>
        /// <param name="holType">是否假期</param>
        /// <param name="fPlan">是否核算</param>
        /// <returns></returns>
        public IList<string> GetAmountYearMonth(string schoolMark, int holType, int fPlan)
        {
            DBEntities db;
            using (db = new DBEntities())
            {
                var list = (from am in db.t_Amount
                            where am.SchoolMark == schoolMark && am.HolType == holType && am.FPlan == fPlan
                            select new
                            {
                                Year = am.FYear,
                                Month = am.FMonth
                            });

                var res = list.Distinct().ToList().OrderByDescending(c => c.Year).ThenByDescending(c => c.Month);
                IList<string> dtList = new List<string>();
                foreach (var re in res)
                {
                    dtList.Add(string.Format("{0}年{1}月", re.Year, re.Month));
                }
                return dtList;
            }
        }

        public string GetVacaMoney(object oAmountIssued)
        {
            double dAmountIssued = 0.0;
            if (oAmountIssued == null || oAmountIssued.ToString() == "")
                return "";
            dAmountIssued = double.Parse(oAmountIssued.ToString());
            return (dAmountIssued - 600).ToString();
        }

        public class MeritPayView
        {
            private int _teacherid;
            private string _teachcode;
            private string _teachname;
            private double? _amountIssued;
            private double? _holidayWork;
            private double? _amountActual;
            private string _holidayWorkContent;
            private string _amountDifferContent;

            public int TeachID
            {
                get { return _teacherid; }
                set { _teacherid = value; }
            }

            public string TeachCode
            {
                get { return _teachcode; }
                set { _teachcode = value; }
            }

            public string TeachName
            {
                get { return _teachname; }
                set { _teachname = value; }
            }

            public double? AmountIssued
            {
                get { return _amountIssued; }
                set { _amountIssued = value; }
            }

            public double? HolidayWork
            {
                get { return _holidayWork; }
                set { _holidayWork = value; }
            }

            public double? AmountActual
            {
                get { return _amountActual; }
                set { _amountActual = value; }
            }

            public string HolidayWorkContent
            {
                get { return _holidayWorkContent; }
                set { _holidayWorkContent = value; }
            }

            public string AmountDifferContent
            {
                get { return _amountDifferContent; }
                set { _amountDifferContent = value; }
            }


        }
    }
}